﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using XSTDZ.ERP.Application.DataContracts;
using XSTDZ.ERP.Infrastructure.Authentication;
using XSTDZ.ERP.Application;
using XSTDZ.ERP.Infrastructure;
using XSTDZ.ERP.Infrastructure.Extentions;
using XSTDZ.ERP.WebApp.Models;
using XSTDZ.ERP.Core.Extentions;
using XSTDZ.ERP.WebApp.Models.Ado;

namespace XSTDZ.ERP.WebApp.Controllers
{
    /// <summary>
    /// 客户控制器
    /// </summary>
     [NoAuthorizated]
    public class ClientController : Controller
    {
         private readonly IClientService clientServiceImpl = ServiceLocator.Instance.GetService<IClientService>();
        //
        // GET: /User/

        public ActionResult Index()
        {
            return View();
        }
        #region 查看详细
        [NoAuthorizated("ClientDetail")]
        public ActionResult ClientDetail(Guid id)
        {
            var client = clientServiceImpl.GetClientInfo(id);
            GetClientProperty(client.ClientProperty.ToString());
            GetProviceList(client.ProvincialID);
            GetCityList(client.ProvincialID);
            return View(client);
        }
        [NoAuthorizated("LinkDetail")]
        public ActionResult LinkDetail(Guid id)
        {
            var genderlst = UserModel.GetUserGenderRadio();
            ViewBag.Gender = genderlst;
            GetCredentialsType("");
            var clientLink = clientServiceImpl.GetClientLink(id);
            ViewBag.ClientId = clientLink.ClientID;
            genderlst.ForEach(g => g.Selected = (g.Value.ToString() == clientLink.Sex.ToString()));
            return View(clientLink);
        }
        #endregion
        #region 添加客户信息
        public ActionResult Add(Guid ?clientId,string orgCode)
        {
            ViewBag.orgCode = orgCode;
            ClientInfoDto client = new ClientInfoDto();
            if (clientId != null && clientId.HasValue)
            {
                Guid id = Guid.Parse(clientId.ToString());
                client = clientServiceImpl.GetClientInfo(id);
                GetClientProperty(client.ClientProperty.ToString());
                GetProviceList(client.ProvincialID);
                GetCityList(client.ProvincialID);
            }
            else
            {
                GetProviceList(0);
                GetCityList(0);
                GetClientProperty("");
            }
            return View(client);
        }
        [HttpPost]
        public ActionResult Add(ClientInfoDto clientDto)
        {
            #region 组织机构ID
		 IOrgService orgServiceImpl = ServiceLocator.Instance.GetService<IOrgService>();
           var org= orgServiceImpl.GetOrg(Request.Form["HidOrgCode"]);
                        ViewBag.orgCode = Request.Form["HidOrgCode"];
                        clientDto.OrgID = org.Id;
	#endregion
            #region 选择数据操作
            //var model = new ProductInBill();
            //var cityId = 0;// model.GetRequestFormValues(this.HttpContext, "CityName_val");
            //var proviceId = 0;// model.GetRequestFormValues(this.HttpContext, "ProvinceName_val");



            //if (Request.Form["ProvinceName_val"] != null && !string.IsNullOrEmpty(Request.Form["ProvinceName_val"]))
            //{
            //    Int32.TryParse(Request.Form["ProvinceName_val"].ToString(), out proviceId);
            //}
            //if (Request.Form["CityName_val"] != null && !string.IsNullOrEmpty(Request.Form["CityName_val"]))
            //{
            //    Int32.TryParse(Request.Form["CityName_val"].ToString(), out cityId);
            //}

            //clientDto.CityID = cityId;
            //clientDto.ProvincialID = proviceId;

                        var model = new ProductOutBillModel();
                        //负责人ID
                        var RPID = model.GetRequestFormValues(this.HttpContext, "ResponsiblePersonName_val"); //SenderName
                        if (!Guid.Empty.Equals(RPID))
                        {
                            clientDto.ResponsiblePersonID = RPID;
                        }
            #endregion

                        #region 由于改动大，默认直接写死，否则时间来不急
                        
                        if (clientDto.ClientPhone.IsEmpty())
                        {
                            clientDto.ClientPhone = "";
                        }
                        if (clientDto.ClientCode.IsEmpty())
                        {
                            clientDto.ClientCode = "";
                        }
                        if (clientDto.ShortName.IsEmpty())
                        {
                            clientDto.ShortName = "";
                        }
                        if (clientDto.ProvincialID<=0)
                        {
                            clientDto.ProvincialID = 2;
                        }
                        if (clientDto.CityID <= 0)
                        {
                            clientDto.CityID = 3;
                        }
                        #endregion
                        //bool isValid = true;
            //foreach (var item in ModelState)
            //{
            //    if (item.Key == "CityID" || item.Key == "ProvincialID")
            //    {
            //        if (item.Value.Errors.Count() != 0)
            //        {
            //            item.Value.Errors.Remove(item.Value.Errors.First());
            //            //break;
            //        }
            //    }
            //    if (item.Value.Errors.Count() != 0)
            //    {
            //        isValid = false;
            //    }
            //}
            if (ModelState.IsValid)
            {
                if (clientDto.Id != null && !clientDto.Id.Equals(Guid.Empty))
                {
                    clientDto.UpdateID = UserModel.GetLoginUserId(this.HttpContext);
                    clientDto.UpdateDate = DateTime.Now;
                    clientServiceImpl.UpdateClient(clientDto);
                }
                else
                {
                    clientDto.CreateID = UserModel.GetLoginUserId(this.HttpContext);
                    //IUserService userServiceImpl = ServiceLocator.Instance.GetService<IUserService>();
                    //clientDto.OrgID = userServiceImpl.GetUserOrg(clientDto.CreateID);
                    clientServiceImpl.AddClient(clientDto);
                }
                ViewBag.PostState = 9;
               // return Content("ok");
            }
            //return Content("0");
            GetClientProperty(clientDto.ClientProperty.ToString());
            GetProviceList(clientDto.ProvincialID);
            GetCityList(clientDto.CityID);
            return View();
        }
        #endregion
        #region 添加客户联系人

        public ActionResult LinkIndex()
        {
            return View();
        }
         //GET: 添加联系人
        public ActionResult AddLink(string orgCode,Guid Id,string type)
        {
            var genderlst = UserModel.GetUserGenderRadio();
            ViewBag.Gender = genderlst;
            ViewBag.OrgCode = orgCode;
            GetCredentialsType("");

            if (type != null &&  type== "edit")
            {
                var clientLink = clientServiceImpl.GetClientLink(Id);
               ViewBag.ClientId = clientLink.ClientID;
               genderlst.ForEach(g => g.Selected = (g.Value.ToString() == clientLink.Sex.ToString()));
               return View(clientLink);
            }
            else
            {
                ViewBag.ClientId = Guid.Empty;
                return View();
            }
        }
         [HttpPost]
        public ActionResult AddLink(ClientLinkDto clientLinkDto)
        {
            if (clientLinkDto.ClientID.Equals(Guid.Empty))
            {
                ModelState.AddModelError("ClientID", "客户不能为空！");
            }
            if (clientLinkDto.MobilePhone.IsEmpty())
            {
                clientLinkDto.MobilePhone = "";
            }
            if (ModelState.IsValid)
            {
                if (clientLinkDto.Id != null && !clientLinkDto.Id.Equals(Guid.Empty))
                {
                    clientLinkDto.UpdateID = UserModel.GetLoginUserId(this.HttpContext);
                    clientLinkDto.UpdateDate = DateTime.Now;
                    clientServiceImpl.UpdateClient(clientLinkDto);
                }
                else
                {
                    clientLinkDto.CreateID = UserModel.GetLoginUserId(this.HttpContext);
                    clientServiceImpl.AddClient(clientLinkDto);
                }
                ViewBag.PostState = 9;
            }
            ViewBag.ClientId = clientLinkDto.ClientID;
            ViewBag.Gender = UserModel.GetUserGenderRadio();
            GetCredentialsType(clientLinkDto.CredentialsType.ToString());
            return View();
        } 
        #endregion
        #region 删除操作
        public ContentResult Delete(Guid clientInfoId)
        {
            this.clientServiceImpl.DeleteClient(clientInfoId);
            return Content("9");
        }
        public ContentResult DeleteLinks(string clientLinkIds)
        {
            string[] arrayIds = clientLinkIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            var guidIds = new List<Guid>();
            arrayIds.Each(id => guidIds.Add(Guid.Parse(id)));
            clientServiceImpl.DeleteClient(guidIds);
            return Content("9");
        }
        #endregion
        #region 返回经销商列表
        // [HttpGet]
        //public ActionResult SelectClients()
        //{
        //    ViewBag.OrgCode = Request.QueryString["orgCode"];
        //    return View();
        //}
         //返回经销商列表
        public ActionResult GetClients()
        {
            #region  EF的查询，效率低下，故暂时放弃不用


            /*
            var condtion = Request.Form["condition"];
            //if (condtion!=null)
            //{
            //  var mm=  Newtonsoft.Json.JsonConvert.DeserializeObject(condtion);

            //  var gg = Newtonsoft.Json.JsonConvert.DeserializeXmlNode(condtion);
            //  var hh = Newtonsoft.Json.JsonConvert.SerializeObject(condtion);

            //  var aa = hh;
            //}

            var clients = clientServiceImpl.GetClientInfos(1, 100, false);
            if (clients != null && clients.Count() != 0)
            {
                var jsonResult = clients.Select(u => new
                {
                    Key = u.Id,
                    ClientName = u.ClientName,
                    ClientCode = u.ClientCode,
                    ShortName = u.ShortName,
                    CityName = u.CityName,
                    ClientAddress = u.ClientAddress,
                    ClientPhone = u.ClientPhone,
                    Email = u.Email,
                    BankName = u.BankName,
                    AccountNnmber = u.AccountNnmber,
                    DeleteState = u.DeleteState
                });

               var target= Newtonsoft.Json.JsonConvert.SerializeObject(jsonResult);
               target = "{\"Rows\":" + target + ",\"Total\":\"10\"}";
               return Content(target);
            }
            return View();
            */
            #endregion

           
            return Content(new BLLQuery().GetClientLists(this.HttpContext));
        }

         //返回经销商联系人列表
        public ActionResult GetClientLinksByClient(Guid clientId)
        {
            var clients = clientServiceImpl.GetClientLinks(clientId).Where(d=>d.Deleted!=1).ToList();
            if (clients != null && clients.Count() != 0)
            {
                var jsonResult = clients;
                clients.Each(t => { t.SexName = t.Sex == 1 ? "男" : "女"; });
                var target = Newtonsoft.Json.JsonConvert.SerializeObject(jsonResult);
                target = "{\"Rows\":" + target + ",\"Total\":\"" + clients.Count()+ "\"}";
                return Content(target);
            }
            return Content("");
        }
        //返回经销商联系人列表
        public ActionResult GetClientLinks()
        {
            #region   EF的查询，效率低下，故暂时放弃不用

            /*
            var clients = clientServiceImpl.GetClientLinks(1, 20, false);
            if (clients != null && clients.Count() != 0)
            {
                var jsonResult = clients;

                var target = Newtonsoft.Json.JsonConvert.SerializeObject(jsonResult);
                target = "{\"Rows\":" + target + ",\"Total\":\"" + clients.Count() + "\"}";
                return Content(target);
            }
            return Content("");
            */
            #endregion
            return Content(new BLLQuery().GetClientLinksLists(this.HttpContext));
        }
        #endregion
        #region 获取行政区域数据
        public ActionResult GetAddressAreas()
        {
            #region   EF的查询，效率低下，故暂时放弃不用
            /*
            var areas = clientServiceImpl.GetAddressAreas(parentId);
            if (areas != null && areas.Count() != 0)
            {
                var target = Newtonsoft.Json.JsonConvert.SerializeObject(areas);
                target = "{\"Rows\":" + target + ",\"Total\":\"" + areas.Count+ "\"}";
                return Content(target);
            }
            return View();
            */
            #endregion
            return Content(new BLLQuery().GetAddressAreas(this.HttpContext));
        }
        #endregion

        #region 弹出选择经销商列表
        public ActionResult SelectClient(string orgCode, string hasSeal="0")
        {
            ViewBag.OrgCode = orgCode;
            ViewBag.HidHasSeal = hasSeal;
            
            return View();
        }
        #endregion

        #region 辅助方法
        
        //获得企业性质
        private void GetClientProperty(string ClientPropertyCode)
        {
            var model = new RefeModel();
            var refeList = model.GetRefeByModuleName(RefeTypeOption.企业性质);
            ViewBag.ClientProperty = model.GetDropDownListItemsByCode(refeList, ClientPropertyCode);
        }
         //获得省级、市级列表
        private void GetProviceList(int proviceID)
        {
            ViewBag.Provoices = new BLLQuery().GetAddressAreas(proviceID, true);
        }

        private void GetCityList(int cityId)
        {
            if (cityId > 0)
            {
                ViewBag.Cities = new BLLQuery().GetAddressAreas(cityId, false);
            }
            else
            {
                ViewBag.Cities = new List<SelectListItem>();
            }
            ViewBag.Cities = ViewBag.Cities?? new List<SelectListItem>();
        }
          [NoAuthorizated("GetCityList")]
        public ActionResult GetCityListOfJson(int cityId)
        {
            if (cityId > 0)
            {
                 var cities= new BLLQuery().GetAddressAreas(cityId, false);
                 var target = Newtonsoft.Json.JsonConvert.SerializeObject(cities);
                 return Content(target);
            }
            return Content("");
        }
         //获得联系人证件类型
          private void GetCredentialsType(string CredentialsType)
          {
              var model = new RefeModel();
              var refeList = model.GetRefeByModuleName(RefeTypeOption.证件类型);
              ViewBag.CredentialsType = model.GetDropDownListItemsByCode(refeList, CredentialsType);
          }
        #endregion


        #region 深圳客户
        //深圳用户
        public ActionResult SZIndex()
        {
            return View();
        }
         //联系人
        public ActionResult SZLinkIndex()
        {
            return View();
        }
        #endregion
    }
}
